package com.daxidi.cn.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.daxidi.cn.utils.ImageVerificationCode;
import com.daxidi.cn.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Api(tags = "验证码模块")
@RestController
@RequestMapping("/api/v1/union/CodeImgController")
public class CodeImgController extends HttpServlet {

	@Autowired
	private RedisUtils redisUtils;

	@ApiOperation(value = "验证码模块  获取验证码接口")
	@GetMapping("/validateCode")
//	public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
//		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
////    session.setAttribute("code",lineCaptcha.getCode());
//		redisUtils.set("scode",lineCaptcha.getCode(),600);
//		System.err.println(lineCaptcha.getCode());
//		ServletOutputStream outputStream = response.getOutputStream();
//		lineCaptcha.write(outputStream);
//		outputStream.close();
//	}
	/*@GetMapping("/validateCode?*")
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		////从HOOT JAR中 获取动态的注册图片
		LineCaptcha code = CaptchaUtil.createLineCaptcha(100,50);
		//获得图片中的正确的注册码
		String scode = (String) code.getCode();
		System.err.println("scode = " + scode);
		//把正确的注册码存到 session作用域中
		HttpSession sess = req.getSession();
		redisUtils.set("scode",scode,600);
//		sess.setAttribute("code",scode);
		//把获得到的图片发送到访问的地方 图片的地址路径写这个类的访问路径
		code.write(resp.getOutputStream());
	}*/

//	@RequestMapping("/validateCode")
//	@ResponseBody
	public void getVerifiCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//         1.生成验证码   用验证码工具类，生成验证码类对象
		ImageVerificationCode ivc = new ImageVerificationCode();
		BufferedImage image = ivc.getImage();  //获取验证码图片
		String code = ivc.getText();	//获取验证码文本
		System.err.println("code = " + code);
		//         2.把验证码上的文本存在redis中
		redisUtils.set("scode",code,600);
		//         3.把验证码图片发送给客户端
		ivc.output(image, response.getOutputStream());//将验证码图片响应给客户端
	}
}
